﻿using AutoMapper;
using BS.Domain.RBAC;
using BS.Infra;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using BS.Write.Api.Extensions;
using BS.Infra.Interface;
namespace BS.Write.Api.Handler.User
{
    public class LoginUserHandler : IRequestHandler<LoginUserRequestDTO, ApiResult>
    {
        private readonly IUserRepository _userRepository;

        private readonly ILogger<LoginUserHandler> _logger;

        private readonly IMapper _mapper;

        private readonly IConfiguration _configuration;
        public LoginUserHandler(IUserRepository userRepository, ILogger<LoginUserHandler> logger, IMapper mapper, IConfiguration configuration)
        {
            _userRepository = userRepository;
            _logger = logger;
            _mapper = mapper;
            _configuration = configuration;
        }
        public async Task<ApiResult> Handle(LoginUserRequestDTO request, CancellationToken cancellationToken)
        {
            try
            {
                var users=await _userRepository.GetAsync(u => u.UserName == request.UserName);
                if (users==null)
                {
                    return ApiResult.Fail("用户名不存在");
                }
                if (users.Password!= request.Password)
                {
                    return ApiResult.Fail("密码错误");
                }

                var response = _mapper.Map<LoginUserReponseDTO>(users);
                response.Token = GenerateJwtToken(response);
                return ApiResult.Ok(response);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "LoginUserHandler");
                throw;
            }
        }

        private string GenerateJwtToken(LoginUserReponseDTO ponse)
        {
            var claims = new[]
            {
            new Claim("Sub", ponse.UserName),
            new Claim("Jti", ponse.UserId.ToString())
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]));
            var creeds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                 _configuration["Authentication:Issuer"],
                _configuration["Authentication:Audience"],
                 claims,
                expires: DateTime.Now.AddHours(8),
                signingCredentials: creeds
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
public class LoginUserRequestDTO:IRequest<ApiResult>
{
    public string UserName { get; set; } = string.Empty;

    public string Password { get; set; } = string.Empty;
}
public class LoginUserReponseDTO
{
    public int UserId { get; set; }

    public string UserName { get; set; } = string.Empty;

    public string Password { get; set; } = string.Empty;

    public int RoleId { get; set; }

    public string Token { get; set; } = string.Empty;
}